package com.powernode.filter.password;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashSet;

/**
 * @Author: powernode
 */
@Component
public class AccountProvider implements AuthenticationProvider {


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        System.out.println("AccountProvider");
        AccountToken accountToken = (AccountToken) authentication;
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        // 这里做判断
        // 查数据库 走业务逻辑e
        AccountToken dbUser = new AccountToken();
        dbUser.setUsername("admin");
        dbUser.setPwd(bCryptPasswordEncoder.encode("123"));
        dbUser.setId(1);
        HashSet<String> set = new HashSet<>();
        set.add("sys:user:add");
        set.add("sys:user:del");
        set.add("sys:user:update");
        dbUser.setAuths(set);
        if (!bCryptPasswordEncoder.matches(accountToken.getCredentials().toString(), dbUser.getPwd())) {
            throw new BadCredentialsException("密码错误");
        }
        // 没问题 就ok
        // 设置登陆了
        dbUser.setAuthenticated(true);
        return dbUser;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        // 非常重要，因为有多个provider 要匹配上类型才会走
        return AccountToken.class.isAssignableFrom(authentication);
    }
}
